package com.sqlloader.views.actions;
import com.sqlloader.activator.Activator;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPage;

import com.sqlloader.views.LoadDataView;
import com.sqlloader.views.SetColumnView;
import com.sqlloader.views.listeners.ColumnComboListener;

public class OpenFileAction extends Action {
	private LoadDataView view;
	public OpenFileAction(String text, ImageDescriptor image,LoadDataView view) {
        super(text, image);
        this.view=view;
    }
	
	public void run() {
		// TODO Auto-generated method stub
		
		FileDialog fd=new FileDialog(this.view.getSite().getShell(),SWT.OPEN );
		fd.setFilterExtensions(new String[]{"*.csv"});
		fd.open();
		String filename=fd.getFilterPath()+"\\"+fd.getFileName();
		view.getDataText().loadFile(filename);
		view.getTableViewer().loadFile(filename);
		view.setDataFilename(filename);
		IWorkbenchPage workbenchPage = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
		SetColumnView setcolumnview=(SetColumnView)workbenchPage.findView("com.sqlloader.views.SetColumnView");
		TableViewer tableviewer=setcolumnview.getTableviewer();
		Table table=tableviewer.getTable();
		table.removeAll();
		int fieldnum=view.getTableViewer().getFieldnum();
		CCombo[] columncombos=new CCombo[fieldnum];
		Text[] ruleTexts=new Text[fieldnum];
		for(int i=0;i<fieldnum;i++)
		{
			TableItem item =new TableItem(table, SWT.NONE);
			
			item.setText(new String[]{"Field"+i,""});
		    TableEditor editor=new TableEditor(table);
		    editor.grabHorizontal = true;
		    editor.grabVertical = true;
	        CCombo combo=new CCombo(table,SWT.DROP_DOWN);
	        
	        
	        editor.setEditor(combo, item, 1);
	        combo.pack();
	        ColumnComboListener listener=new ColumnComboListener(combo,i);
	        combo.addListener(SWT.FocusIn,listener);
	        combo.addSelectionListener(listener);
	        columncombos[i]=combo;
	        
	        editor=new TableEditor(table);
		    editor.grabHorizontal = true;
		    editor.grabVertical = true;
		    Text ruleText=new Text(table,SWT.NONE);
		    editor.setEditor(ruleText, item, 2);
		    ruleTexts[i]=ruleText;
		}
		setcolumnview.setColumncombos(columncombos);
		setcolumnview.setRuleTexts(ruleTexts);
	}

}
